package com.base.cn.platform.os.service.user.signin;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.dao.user.signin.CusUserSignInDao;
import com.base.cn.platform.os.entity.user.signin.CusUserSignIn;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 签到Biz
 * @author ll
 * @date 2018/5/25 14:18
 */
@Service
public class CusUserSignInBiz extends BaseBiz<CusUserSignIn,CusUserSignInDao> {


    @Autowired
    private CusUserBiz cusUserBiz;

    /**
     * 保存签到时间
     * @param userSignIn
     * @return
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public CusUserSignIn saveUserSignIn(CusUserSignIn userSignIn){
        this.save(userSignIn);
        cusUserBiz.updateUserNumberOfStatistics(userSignIn.getUserId(),"signNum",1);
        return userSignIn;
    }

    /**
     * 搜索签到列表
     * @param userSignIn 用户签到数据
     * @return
     */
    public List<CusUserSignIn> selectUserSignInList(CusUserSignIn userSignIn){
        String whereSql = " 1=1 ";
        if (ObjectUtils.isNotEmpty(userSignIn)){
            if (DataUtil.idIsNotNull(userSignIn.getUserId())){
                whereSql += " and  userId ="+userSignIn.getUserId();
            }
            if (ObjectUtils.isNotEmpty(userSignIn.getSignDate())){
                String time1 = new SimpleDateFormat("yyyy-MM-dd").format(userSignIn.getSignDate());
                whereSql += " and  signDate like concat('%','"+time1+"','%')";
            }
        }
        List<CusUserSignIn> userSignIns = this.find(whereSql,1,null);
        return userSignIns;
    }

    /**
     * 根据用户Id搜索用户的签到记录
     * @param userId
     * @return
     */
    public List<CusUserSignIn>  querySignInDateByUserId(BigDecimal userId){
        if(ObjectUtils.isNotEmpty(userId)){
            CusUserSignIn cusUserSignIn = new CusUserSignIn();
            cusUserSignIn.setUserId(userId);
            return this.selectUserSignInList(cusUserSignIn);
        }
        return null;
    }

    /**
     * 获取用户的某个月的签到记录
     * @param userId 用户ID
     * @param year 年
     * @param month 月
     * @return List<CusUserSignIn>
     */
    public List<CusUserSignIn> findUserMonthSignList(BigDecimal userId,String year,String month){
        if(month.trim().length()<2){
            month = "0"+month;
        }
        List<CusUserSignIn> cusUserSignIns = this.find(" userId = "+userId +"  and signDate like '"+year+"-"+month+"%'",null,null);
        return cusUserSignIns;
    }
}
